#!/usr/bin/env python3
# verify snapshot xlsx file with new status file

import sys
from openpyxl import load_workbook, Workbook


def merge_xlsx_by_first_column(input_file, new_data, output_file=None):
    """
    读取已有xlsx文件，基于第一列的值与 new_data 合并，并保存为xlsx。

    参数：
        input_file (str): 要读取的 xlsx 文件路径
        new_data (list[list]): 含表头的新数据（二维列表）
        output_file (str): 保存路径，若不指定则覆盖原文件
    """

    # 读取原文件
    wb = load_workbook(input_file)
    ws = wb.active

    # 读取表格内容到列表
    existing_data = [list(row) for row in ws.iter_rows(values_only=True)]
    
    # 提取表头
    header_old = existing_data[0]
    header_new = new_data[0][1:]  # 跳过第一列以避免重复

    # 创建一个合并后的表头
    merged_header = header_old + header_new

    # 将 new_data 转成字典（基于第一列）
    lookup = {row[0]: row[1:] for row in new_data[1:]}

    merged_rows = [merged_header]

    # 遍历原文件的内容，将 new_data 匹配部分合并
    for row in existing_data[1:]:
        key = row[0]
        extra = lookup.get(key, [""] * len(header_new))  # 没匹配上用空白填充
        merged_rows.append(row + extra)

    # 用新结果覆盖表格内容
    wb = Workbook()
    ws = wb.active
    for row in merged_rows:
        ws.append(row)

    # 保存文件
    output_file = output_file or input_file
    wb.save(output_file)
    print(f"合并完成，文件已保存：{output_file}")


def main():
    if len(sys.argv) != 3:
        print("Usage: verify-changes.py <snapshot_xlsx> <new_status_file>")
        sys.exit(1)
    snapshot_xlsx = sys.argv[1]
    new_status_file = sys.argv[2]

    status_table = [
        ['路径', '更新后状态']
    ]
    with open(new_status_file, 'r') as sf:
        for line in sf:
            line = line.strip()
            if not line:
                continue
            path, owners = line.split('\t')
            path = path.strip()
            owners = owners.strip()
            status_table.append([path, owners])
    merge_xlsx_by_first_column(snapshot_xlsx, status_table, "verify_snapshot.xlsx")


if __name__ == "__main__":
    main()
